//
//  BaseModuleViewController.m
//  EnjoyArkUIXIOS
//
//  Created by Dordly on 2024/1/30.
//

#import "BaseModuleViewController.h"
#import <Photos/Photos.h>
#import <libarkui_ios/StageApplication.h>
#import <libarkui_ios/BridgePlugin.h>
#import "BridgeClass.h"
#import "PublicAlertView.h"
//#import "ImgTools.h"
#import "EffectSelectionModel.h"
#import "DynamicShowViewController.h"
//#import <SSZipArchive/SSZipArchive.h>
#import "OneToMoreViewController.h"

#define doc_path(_fileOrFolder) [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:_fileOrFolder]

@interface BaseModuleViewController () <IMessageListener, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, strong) BridgeClass* plugin;

@property (nonatomic, strong) UIView *mainView;
@property (nonatomic, strong) StageViewController *stageVC;
@property (nonatomic, assign) CGFloat statusBarHeight;

@property (nonatomic, strong) UIImage *needEffectImage;
@property (nonatomic, strong) PublicAlertView *publicAlertView;

@property (nonatomic, strong) NSMutableArray *inputResultArray;

@property (nonatomic, assign) BOOL isHaveDynamicContent;

@end

@implementation BaseModuleViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.statusBarHeight = 0;
    if (self.isShowNavigationBar) {
        [self setNavigationBarWithCenterTitle:self.titleName];
        self.statusBarHeight = [self getStatusBarHeight] + [self getNavigationBarHeight];
    }
    [self createUI];
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = !self.isShowNavigationBar;
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = YES;
    [self setNewOrientation:YES];
    if ([self.titleName isEqualToString:@"动态化"]) {
        [self isHaveDynamicDocumentInfo];
    }
}

- (void)createUI {
    CGFloat top = self.isShowNavigationBar ? self.statusBarHeight : 0;
    self.mainView = [[UIView alloc] init];
    self.mainView.frame = CGRectMake(0, top, self.view.frame.size.width, self.view.frame.size.height - top);
    [self.view addSubview:self.mainView];
    self.stageVC = [[StageViewController alloc] initWithInstanceName:self.instanceName];
    self.stageVC.view.frame = CGRectMake(0, 0, self.mainView.frame.size.width, self.mainView.frame.size.height);
    self.stageVC.view.backgroundColor = [UIColor whiteColor];
    [self.mainView addSubview:self.stageVC.view];
    [self addChildViewController:self.stageVC];
    
    // 建立与ArkUI侧同名的平台桥接，即可用于消息传递
    self.plugin = [[BridgeClass alloc] initBridgePlugin:@"Bridge" bridgeManager:[self.stageVC getBridgeManager]];
    self.plugin.messageListener = self;
    [self.view addSubview:self.publicAlertView];
}

- (void)setIsPortrait:(BOOL)isPortrait {
    CGFloat top = self.isShowNavigationBar ? self.statusBarHeight : 0;
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height - top;
    if ((isPortrait && height < width) || (!isPortrait && width < height)) {
        width = self.view.frame.size.height;
        height = self.view.frame.size.width - top;
    }
    self.mainView.frame = CGRectMake(0, top, width, height);
}

- (PublicAlertView *)publicAlertView {
    if (!_publicAlertView) {
        _publicAlertView = [[PublicAlertView alloc] initWithFrame:self.view.frame mainTitle:@""];
    }
    return _publicAlertView;
}


// 监听ArkUI侧发来的消息
#pragma mark - listener
- (NSString*)onMessage:(id)data {
    NSString *dataStr;
    if ([data isKindOfClass:[NSString class]]) {
        dataStr = data;
    }
    NSData *dataInfo = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    id resultData = [NSJSONSerialization JSONObjectWithData:dataInfo options:NSJSONReadingMutableContainers error:nil];
    NSArray *array = [NSArray array];
    if ([resultData isKindOfClass:[NSDictionary class]]) {
        id result = [resultData objectForKey:@"result"];
        if ([result isKindOfClass:[NSArray class]]) {
            array = result;
        }
        if ([result isKindOfClass:[NSString class]]) {
            NSData* data = [result dataUsingEncoding:NSUTF8StringEncoding];
            id dataValue = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([dataValue isKindOfClass:[NSArray class]]) {
                array = dataValue;
            }
        }
    }
    if ([resultData isKindOfClass:[NSArray class]]) {
        array = resultData;
    }
    if ([resultData isKindOfClass:[NSString class]] && [resultData containsString:@":"]) {
        array = [resultData componentsSeparatedByString:@":"];
    }
    if ([dataStr containsString:@"getArkUI-goBack"]) {
        [self.navigationController popViewControllerAnimated:YES];
        return [NSString stringWithFormat: @"oc onMessage success: %@", data];
    }
    if ([dataStr containsString:@"Hello ArkUI-X!"]) {
        [self getCamera];
        return [NSString stringWithFormat: @"oc onMessage success: %@", data];
    }
    if ([dataStr containsString:@"getDynamic-DownType:"]) {
        if ([dataStr containsString:@"delete"]) {
            [self deleteDocumentInfoWithPathStr:@"files/arkui-x"];
            self.publicAlertView.titleStr = @"清除成功";
            [self.publicAlertView showView];
        } else {
            [self.plugin sendMessage:@[@"正在下载中……"]];
            if([dataStr containsString:@"0"]) { // 本地解压缩下载
                [self unZip];
            } else { // 云端请求下载
                [self downloadFile];
            }
        }
        return [NSString stringWithFormat: @"oc onMessage success: %@", data];
    }
    if (self.needEffectImage && array.count > 0){
        [self equalTypeArray:array];
    } else {
        self.publicAlertView.titleStr = @"请先上传一张图片";
        [self.publicAlertView showView];
    }
    NSLog(@"%@", array);
    return [NSString stringWithFormat: @"oc onMessage success: %@", data];
}

// 删除缓存
- (void)deleteDocumentInfoWithPathStr:(NSString *)pathStr {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for (NSString *path in files) {
        NSError *error = nil;
        if (![path containsString:pathStr]) {
            continue;
        }
        NSString *filePath = [cachePath stringByAppendingPathComponent:path];
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        }
    }
    [self isHaveDynamicContent];
}

// 获取内容
- (void)isHaveDynamicDocumentInfo {
    NSString *resultLocal = doc_path(@"files/arkui-x");
    NSFileManager *fm = [NSFileManager defaultManager];
    self.isHaveDynamicContent = [fm fileExistsAtPath:resultLocal];
    if (self.isHaveDynamicContent && self.plugin) {
        [self.plugin sendMessage:@[@"展示效果呈现"]];
    }
}

- (long)haveFileSize {
    NSString *resultLocal = doc_path(@"files/arkui-x");
    NSFileManager *fm = [NSFileManager defaultManager];
    self.isHaveDynamicContent = [fm fileExistsAtPath:resultLocal];
    long fileSize = 0;
    if ([fm fileExistsAtPath:resultLocal]) {
        NSDictionary *dic = [fm attributesOfItemAtPath:resultLocal error:nil];
        fileSize = [[dic objectForKey:@"NSFileSize"] longLongValue];
    }
    return fileSize;
}

- (void)unZip {
    if (self.isHaveDynamicContent) {
        [self pushNextPage];
        return;
    }
    // 解压缩
    NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"arkui-x" ofType:@"zip"];
    NSString *resultLocal = doc_path(@"files/arkui-x");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [SSZipArchive unzipFileAtPath:pathStr toDestination:resultLocal
//                      progressHandler:nil
//                    completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (succeeded) { // 解压成功后，进入效果界面
//                    [self pushNextPage];
//                }
//            });
//        }];
    });
}

- (void)pushNextPage {
    [self.plugin sendMessage:@[@"下载完成"]];
    [UIView animateWithDuration:0.25 animations:^{
        [self.plugin sendMessage:@[@"展示效果呈现"]];
        DynamicShowViewController *dynamicVC = [[DynamicShowViewController alloc] init];
        dynamicVC.moduleName = @"fang_application";
        dynamicVC.abilityName = @"Fang_applicationAbility";
        dynamicVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:dynamicVC animated:YES];
    }];
}

// 下载zip文件
- (void)downloadFile {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSURL *url = [NSURL URLWithString:@"https://note.youdao.com/yws/public/resource/031d59c49404e94692b71348801a3bf3/xmlnote/WEBRESOURCE8c1089c86b5bb16e4a6739f43fb80f4f/7488"];
        NSError *error = nil;
        NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
        if (!error) {
            NSString *zipPath = doc_path(@"zipfile.zip");
            [data writeToFile:zipPath options:0 error:&error];
            if (!error) {
                // 解压缩
                NSString *resultLocal = doc_path(@"files/arkui-x");
//                [SSZipArchive unzipFileAtPath:zipPath toDestination:resultLocal
//                              progressHandler:nil
//                            completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        if (succeeded) { // 解压成功后，进入效果界面
//                            [self deleteDocumentInfoWithPathStr:@"zipfile.zip"];
//                            [self pushNextPage];
//                        }
//                    });
//                }];
            } else {
                NSLog(@"error saving file %@", error);
            }
        } else {
            NSLog(@"error dowloading zip file %@", error);
        }
    });
}

#pragma mark - 对比查询可渲染的效果 -
- (void)equalTypeArray:(NSArray *)typeArray {
    [self crearFile];
    self.inputResultArray = [NSMutableArray arrayWithCapacity:0];
    if (typeArray.count <= 0 || !self.needEffectImage) {
        [self.plugin sendMessage:[self.inputResultArray copy]];
        return;
    }
    NSArray *effectArray = [EffectSelectionModel inputEffectDataArray];
    NSMutableArray *inputResultArray = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < typeArray.count; i++) {
        for (EffectSelectionModel *model in effectArray) {
            if (![typeArray[i] isEqualToString:model.titleStr]) {
                continue;
            }
//            UIImage *imgStr = [ImgTools opencvNormalImage:self.needEffectImage processType:model.effectType effectName:model.titleStr];
//            if (imgStr) {
//                [inputResultArray addObject:imgStr];
//            }
        }
    }
    // 获取路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = paths.firstObject;
    NSString *uniquePath = [path stringByAppendingPathComponent:@"opencvImage"];
    NSFileManager *file = [NSFileManager defaultManager];
    NSArray *fileArray = [file contentsOfDirectoryAtPath:uniquePath error:NULL];
    for (NSString *pathStr in fileArray) {
        NSString *path = [uniquePath stringByAppendingPathComponent:pathStr];
        NSLog(@"path address = %@", path);
        if (![path containsString:@"file:///private"]) {
            path = [NSString stringWithFormat:@"file:///private%@", path];
        }
        [self.inputResultArray addObject:path];
    }
    [self.plugin sendMessage:[self.inputResultArray copy]];
}

- (void)crearFile {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for (NSString *path in files) {
        NSError *error = nil;
        if (![path containsString:@"opencvImage"]) {
            continue;
        }
        NSString *filePath = [cachePath stringByAppendingPathComponent:path];
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        }
    }
}

- (void)onMessageResponse:(id)data {
    NSLog(@"arkui-x-------------%@", data);
}

- (void)getCamera {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"上传图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    // 相册
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        picker.allowsEditing = YES;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVC addAction:albumAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    UIDevice *device = [UIDevice currentDevice];
    if (device.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {
        UIPopoverPresentationController *popover = alertVC.popoverPresentationController;
        if (popover) {
            popover.sourceView = self.view;// 在哪个view上展示
            popover.sourceRect = CGRectMake(0, 0, 100, 100);// 自定义frame
            popover.permittedArrowDirections = UIPopoverArrowDirectionDown;//箭头指向
        }
        return;
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    [self dismissViewControllerAnimated:YES completion:^{
        if (@available(iOS 11.0, *)) {
            NSURL *imgStr = info[UIImagePickerControllerImageURL];
            self.needEffectImage = info[UIImagePickerControllerOriginalImage];
            [self.plugin sendMessage:@[imgStr.absoluteString]];
        } else {
            // Fallback on earlier versions
        }
        NSLog(@"info---------------\n %@", info);
    }];
}


@end
